import time
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from selenium.common import InvalidArgumentException, WebDriverException, NoSuchElementException
from selenium.webdriver.support.wait import WebDriverWait


class Base:
    def __init__(self, browser):
        # 打开浏览器, 设置driver
        if browser == "chrome":
            self.driver = webdriver.Chrome()
        elif browser == "firefox":
            self.driver = webdriver.Firefox()
        elif browser == "edge":
            self.driver = webdriver.Edge()
        else:
            print("浏览器打开失败")
            self.driver = None

    def max(self):
        self.driver.maximize_window()

    def get_url(self, url):
        # 请求目标网址
        try:
            self.driver.get(url)
        except (InvalidArgumentException, WebDriverException):
            print("网址错误")

    def find_ele(self, locator):
        # 定位元素
        try:
            ele = self.driver.find_element(*locator)
            print(ele.get_attribute)
            return ele
        except NoSuchElementException:
            print("元素定位失败")

    def click(self, locator):
        # 元素点击操作
        element = self.find_ele(locator)
        if element is not None:
            element.click()
        else:
            print("元素定位失败")

    def get_attribute(self, locator, att):
        # 获取元素属性
        ele = self.find_ele(locator)
        if ele is not None:
            ele.get_attribute(att)

    def forward(self):
        # 前进
        self.driver.forward()

    def back(self):
        # 后退
        self.driver.back()

    def refresh(self):
        # 刷新
        self.driver.refresh()

    def close(self):
        # 关闭页面
        self.driver.close()

    def find_element(self, locator, timeout=5):
        try:
            ele = WebDriverWait(self.driver, timeout, 2).until(EC.presence_of_element_located(locator))
            print(ele.get_attribute("outerHTML"))
        except NoSuchElementException:
            print("元素不存在")

    def send_keys(self, locator, text):
        if self.find_ele(locator):
            self.find_ele(locator).send_keys(text)
        else:
            print("元素输入失败")

    def clear(self, locator):
        if self.find_ele(locator):
            self.find_ele(locator).clear()
        else:
            print("元素不存在")

    def quit(self):
        self.driver.quit()

    def static(self, seconds=3):
        time.sleep(seconds)


if __name__ == '__main__':
    A = ('id', 'keyword')
    B = ('name', 'imageField')
    base = Base("chrome")
    base.get_url("http://139.129.26.163/  ")
    base.max()
    base.find_ele(A)
    base.get_attribute(A, "outerHTML")
    base.send_keys(A, '移动电源')
    base.click(B)
    base.static()
    base.back()
    base.static()
    base.refresh()
    base.static()
    base.forward()
    base.quit()
